package com.qi.demo01.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author zjq
 * @date 2020/3/30 21:58
 * <p>
 * <p>
 * CAS问题加入版本控制
 */
public class CASDemo {
    public static void main(String[] args) {
        //integerAtomicStampedReference 注意：如果泛型是一个包装类，注意对像的引用。
        //正常在业务操作中，这里比较的都是一个个对象。
        AtomicStampedReference<Integer> integerAtomicStampedReference = new AtomicStampedReference<>(20, 1);

        new Thread(() -> {
            int stamp = integerAtomicStampedReference.getStamp();//获得版本号
            System.out.println("a1=>" + stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(integerAtomicStampedReference.compareAndSet(20, 22, integerAtomicStampedReference.getStamp(),
                    integerAtomicStampedReference.getStamp() + 1) + "a2======================");
            System.out.println("a2=>" + integerAtomicStampedReference.getStamp());
            System.out.println(integerAtomicStampedReference.compareAndSet(22, 20, integerAtomicStampedReference.getStamp(),
                    integerAtomicStampedReference.getStamp() + 1) + "a3======================");
            System.out.println("a3=>" + integerAtomicStampedReference.getStamp());
        }, "a").start();

        new Thread(() -> {
            int stamp = integerAtomicStampedReference.getStamp();
            System.out.println("b1=>" + stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(integerAtomicStampedReference.compareAndSet(20, 24,
                    integerAtomicStampedReference.getStamp(),
                    integerAtomicStampedReference.getStamp() + 1) + "b2======================");
            System.out.println("b2=>" + integerAtomicStampedReference.getStamp());
        }, "b").start();
    }
}
